home *** CD-ROM | disk | FTP | other *** search
/ Tech Arsenal 1 / Tech Arsenal (Arsenal Computer).ISO / tek-01 / strlib.zip / STRFIND.C < prev    next >
Text File  |  1993-01-04  |  2KB  |  51 lines

  1.  
  2. /*  File   : strfind.c
  3.     Author : Richard A. O'Keefe.
  4.     Updated: 23 April 1984
  5.     Defines: strfind()
  6.  
  7.     strfind(src, pat) looks for an instance of pat in src.  pat is not a
  8.     regex(3) pattern, it is a literal string which must be matched exactly.
  9.     As a special hack to prevent infinite loops, the empty string will be
  10.     found just once, at the far end of src.  This is hard to justify.  The
  11.     result is a pointer to the first character AFTER the located instance,
  12.     or NullS if pat does not occur in src.  The reason for returning the
  13.     place after the instance is so that you can count the number of instances
  14.     by writing
  15.         _str2pat(ToBeFound);
  16.         for (p = src, n = 0; p = strfind(p, NullS); n++) ;
  17.     If you want a pointer to the first character of the instance, it is up
  18.     to you to subtract strlen(pat).
  19.  
  20.     If there were a strnfind it wouldn't have to look at all the characters
  21.     of src, this version does otherwise it could miss the closing NUL.
  22. */
  23.  
  24. #include "strings.h"
  25. #include "_str2pat.h"
  26.  
  27. char *strfind(src, pat)
  28.     char *src, *pat;
  29.     {
  30.         register char *s, *p;
  31.         register int c, lastch;
  32.  
  33.         pat = _str2pat(pat);
  34.         if (_pat_lim < 0) {
  35.             for (s = src; *s++; ) ;
  36.             return s-1;
  37.         }
  38.         /*  The pattern is non-empty  */
  39.         for (c = _pat_lim, lastch = pat[c]; ; c = _pat_vec[c]) {
  40.             for (s = src; --c >= 0; )
  41.                 if (!*s++) return NullS;
  42.             c = *s, src = s;
  43.             if (c == lastch) {
  44.                 for (s -= _pat_lim, p = pat; *p; )
  45.                     if (*s++ != *p++) goto not_yet;
  46.                 return s;
  47. not_yet:;   }
  48.         }
  49.     }
  50.  
  51.